package soulkun.library.custom.view

import android.annotation.SuppressLint
import android.content.Context
import android.util.AttributeSet
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.RadioButton
import android.widget.RadioGroup
import soulkun.library.utils.log.LogUtils

class MultiRadioGroup: RadioGroup {

    companion object{
        const val TAG = "MultiRadioGroup"
    }

    private var checkedId = -1
    private var onCheckedChangeListener: OnCheckedChangeListener? = null

    constructor(context: Context) : super(context)

    constructor(context: Context, attributeSet: AttributeSet) : super(context, attributeSet)

    override fun setOnCheckedChangeListener(listener: OnCheckedChangeListener?) {
        onCheckedChangeListener = listener
    }

    @SuppressLint("ClickableViewAccessibility")
    override fun addView(child: View, index: Int, params: ViewGroup.LayoutParams) {
        if (child is LinearLayout) {
            val childCount = child.childCount
            for (i in 0 until childCount) {
                val view = child.getChildAt(i)
                if (view is RadioButton) {
                    view.setOnClickListener {
                        checkedId = id
                        view.isChecked = true
                        checkRadioButton(this, view)
                        if (onCheckedChangeListener != null) {
                            onCheckedChangeListener!!.onCheckedChanged(this@MultiRadioGroup, view.id)
                        }
                    }
                }
            }
        }
        super.addView(child, index, params)
    }

    private fun checkRadioButton(viewGroup: ViewGroup, radioButton: RadioButton) {
        val radioCount = viewGroup.childCount
        for (i in 0 until radioCount) {
            val child = viewGroup.getChildAt(i)
            if (child is RadioButton) {
                if (child != radioButton) {
                    child.isChecked = false
                }
            } else if (child is LinearLayout) {
                checkRadioButton(child, radioButton)
            }
        }
    }

}


